import axios from 'axios';
import { message } from 'ant-design-vue';
import { useUser } from '@/pinia-store/user';
import route from '@/router/index';

const request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 20000
})

request.interceptors.request.use(
  config => {
    const whitePages = ['/login']
    if (useUser().token) {
      config.headers['token'] = useUser().token
    } else if (whitePages.indexOf(route.currentRoute.value.path) === -1) {
      route.replace('/login')
      useUser().clearCache()
      return Promise.reject('未授权，请登录！')
    }

    return config
  },
  error => {
    // 请求错误处理
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    // 接口需要弹窗提示
    let messageBoxUrl = [

    ]
    // 接口不需要任何提示
    let noMessageApi = [
    
    ]
    switch(response.data.code) {
    case 0:
      break;
    case 401:
      // 登录过期
      route.replace('/login')
      useUser().clearCache()
      message.error(response.data.msg);
      return Promise.reject(response)
    default:
      if (messageBoxUrl.indexOf(response.config.url) !== -1) {
        // 单独确认弹窗提示
      } else if (noMessageApi.indexOf(response.config.url) !== -1) {
        // 不需要提示
        return Promise.reject(response)
      } else {
        if (response.data.msg) {
          // 普通信息提示
          message.error(response.data.msg);
        }
      }
      return Promise.reject(response)
    }
    return response
  },
  error => {
    return Promise.reject(error)
  }
)

export default request